package com.ziroom.finance.rabbitmq.common.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;

/**
 * copied from financialCenter
 * used for file read and write
 */
public class FileUtil {
	/**
	 * 获得指定文件的byte数组
	 */
	public static byte[] getBytes(String filePath) {
		byte[] buffer = null;
		FileInputStream fis = null;
		ByteArrayOutputStream bos = null;
		try {
			File file = new File(filePath);
			fis = new FileInputStream(file);
			bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			//fis.close();
			//bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} 
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return buffer;
	}
	
	
	public static byte[] toByteArray(InputStream fis) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
		byte[] b = new byte[1000];
		int n;
		while ((n = fis.read(b)) != -1) {
			bos.write(b, 0, n);
		}
		fis.close();
		bos.close();
		byte[] buffer = bos.toByteArray();
		
	    return buffer;
	}

	/**
	 * 上传图片到服务器
	 * 
	 * @param urlstr
	 * @param bytes
	 * @param filename
	 * @return
	 */
	public static String httpUploadTo(String urlstr, byte[] bytes, String filename) {
		String text = null;
		try {
			URL url = new URL(urlstr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			// 发送POST请求必须设置如下两行 ,请求头
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");

			conn.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=---------------------------------0xKhTmLbOuNdArY");
			conn.setConnectTimeout(10000);
			conn.connect();
			OutputStream out = conn.getOutputStream();

			// 请求体 Postbody
			StringBuilder sb = new StringBuilder();
			sb.append("-----------------------------------0xKhTmLbOuNdArY\r\n");
			sb.append("Content-Disposition: form-data; name=\"iosImage\"; fileName=\"" + filename + "\"\r\n");
			sb.append("Content-Type: image/jpeg\r\n\r\n");
//			out.write(sb.toString().getBytes("utf-8"));
			out.write(bytes);
//			out.write("\r\n-----------------------------------0xKhTmLbOuNdArY--\r\n".getBytes("utf-8"));
			out.flush();
			out.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				if (text != null) {
					text += line;
				} else {
					text = line;
				}
			}
			conn.disconnect();
		} catch (Exception e) {
			System.out.println("发送文件出现异常！" + e);
			e.printStackTrace();
		}
		return text;
	}

	/**
	 * @desc 获取文件后缀
	 * @param fileName
	 * @return
	 * @author dfx
	 */
	public static String getExtensionName(String fileName) {
		if ((fileName != null) && (fileName.length() > 0)) {
			int dot = fileName.lastIndexOf('.');
			if ((dot >-1) && (dot < (fileName.length() - 1))) {
				return fileName.substring(dot + 1);
			}
		}
		return fileName;
	}

	/**
	 * 注:暂时不使用
	 * @desc 判断图片是否满足指定格式后缀
	 * @param imageType
	 * @return
	 * @author dfx
	 */
	public static boolean isAllowImageType(String imageType){
		//读取预定义文件类型
		String[] imageTypes = PropertiesUtil.getPropValAsString("imageType").split(",");
		if(!StringUtil.isBlank(imageType)){
			return Arrays.asList(imageTypes).contains(imageType);
		}else{
			return false;
		}
	}

	/**
	 * @desc 生成随机文件名
	 * @param fileName
	 * @return
	 * @author dfx
	 */
	public static String getRandomFileName(String fileName){
		String extensionName = getExtensionName(fileName);
		String newFileName = "";
		if((extensionName != null) && (extensionName.length() > 0)){
			newFileName = System.currentTimeMillis() + "";
			newFileName += ".";
			newFileName += extensionName;
		}
		return newFileName;
	}




	public static void main(String[] args) {
		//String pathName = "C:\\Users\\zhaok\\Desktop\\test.jpg";
		//String str = "你好啊123qweqwe";
		//System.out.println(httpUploadTo("http://www.ziroom.com/?_p=api&_a=uploadImg", getBytes(pathName), "15.jpg"));
		System.out.println(getExtensionName("423455432efd....png"));
		System.out.println(isAllowImageType("png"));
		System.out.println(getRandomFileName("423455432efd....png"));
	}
}
